package com.qiyue.admin.biz.base;

import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.qiyue.admin.constant.AdminCommonConstant;
import com.qiyue.admin.constant.RedisConstant;
import com.qiyue.admin.entity.base.Menu;
import com.qiyue.admin.repository.base.MenuRepsoitory;
import com.qiyue.common.biz.BaseBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by y747718944 on 2018/2/7
 */
@Service
@Transactional(rollbackOn = Exception.class)
public class MenuBiz extends BaseBiz<MenuRepsoitory,Menu,Long> {

    @Autowired
    private GroupTypeBiz groupTypeBiz;

    @Override
    @Cache(key= RedisConstant.PERMISSION_MENU )
    public List<Menu> findAll() {
        return super.findAll();
    }
    @Override
    @CacheClear(keys = { RedisConstant.PERMISSION_MENU , RedisConstant.PERMISSION })
    public Menu save(Menu entity) {
        if (AdminCommonConstant.ROOT == entity.getParentId()) {
            entity.setPath("/" + entity.getCode());
        } else {
            Menu parent = this.findOne(entity.getParentId());
            entity.setPath(parent.getPath() + "/" + entity.getCode());
        }
        return super.save(entity);
    }



    /**
     * 获取用户可以访问的菜单
     *
     * @param userId
     * @return
     */
    @Cache(key = "permission:menu:u{1}")
    public List<Menu> getUserAuthorityMenuByUserId(Long userId) {
        Map<String,Object> params=new HashMap<>();
        params.put("EQ_resourceAuthority.resourceType","menu");
        params.put("EQ_resourceAuthority.authorityType","group");
          return this.findDistinctList(params);
    }


    /**
     * 根据用户获取可以访问的系统
     *
     * @param userId
     * @return
     */
    public List<Menu> getUserAuthoritySystemByUserId(Long userId) {
        Map<String,Object> params=new HashMap<>();
        params.put("EQ_resourceAuthority.resourceType","menu");
        params.put("EQ_resourceAuthority.authorityType","group");
        params.put("EQ_parentId",-1);
        return this.findDistinctList(params);
    }


    //获取分组对应的菜单内容
    public List<Menu> selectMenuByAuthorityId(Long authorityId,String authorityType){
        Map<String,Object> params=new HashMap<>();
        params.put("EQ_resourceAuthority.authorityType",authorityType);
        params.put("EQ_resourceAuthority.authorityId",authorityId);
        params.put("EQ_resourceAuthority.resourceType","menu");
        return this.findDistinctList(params);
    }

}
